package by.grsu.crs.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;

import by.grsu.crs.form.SignUpStepTwoForm;
import by.grsu.crs.model.ConfidentialData;
import by.grsu.crs.model.User;
import by.grsu.crs.service.AuthenticationService;
import by.grsu.crs.service.impl.AuthenticationServiceImpl;

public class SignUpStepTwoAction extends Action {
	private final static String SUCCESS = "success";
    private final static String FAILURE = "failure";
    private final static String CANCEL = "cancel";
    private final static String STEPBACK = "stepback";
    
    public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
    	SignUpStepTwoForm signUpStepTwoForm = (SignUpStepTwoForm) form;
    	if(isCancelled(request)) {
    		return mapping.findForward(CANCEL);
    	}
    	
    	ActionErrors errors = form.validate(mapping, request);
    	if(!errors.isEmpty()) {
    		saveErrors(request, errors);
    		return mapping.findForward(FAILURE);
    	}
    	
    	User client = (User) request.getSession().getAttribute("client");
    	if(client != null) {
    		AuthenticationService authService = new AuthenticationServiceImpl();
    		
    		ConfidentialData confData = new ConfidentialData(signUpStepTwoForm.getPassportNumber(), 
    				Integer.parseInt(signUpStepTwoForm.getCreditCard()), signUpStepTwoForm.getName(), 
    				signUpStepTwoForm.getSurname(), signUpStepTwoForm.getPatronymic(), 
    				signUpStepTwoForm.getBirthdateDate(), signUpStepTwoForm.getPhone(), 
    				signUpStepTwoForm.getCountry(), Integer.parseInt(signUpStepTwoForm.getZip()), 
    				signUpStepTwoForm.getState(), signUpStepTwoForm.getCity(), 
    				signUpStepTwoForm.getStreet(), signUpStepTwoForm.getHouse(), 
    				signUpStepTwoForm.getApartment());
    		
    		if(authService.signUpStepTwo(confData, client)) {
    			return mapping.findForward(SUCCESS);
    		} else {
    			return mapping.findForward(FAILURE);
    		}
    	} else {
    		errors.add("email", new ActionMessage("error.email.step-first"));
    		return mapping.findForward(STEPBACK);
    	}
    }
}
